package com.atguigu.gmall.product.impl;

import com.atguigu.gmall.product.service.TestService;
import com.atguigu.gmall.product.vo.FreeMarkVO;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URL;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void testLock() {
        //10后面不加L
        RLock lock = redissonClient.getLock("num");
//        lock.lock(10,TimeUnit.SECONDS);
        try {
            lock.tryLock(100, 10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            String num = stringRedisTemplate.opsForValue().get("num");
            if (StringUtils.isEmpty(num)) {
                return;
            }
            int numValue = Integer.parseInt(num);
            stringRedisTemplate.opsForValue().set("num", String.valueOf(++numValue));
        } finally {
            lock.unlock();
        }

    }

    @Override
    public String testReadLock() {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("anyRWLock");
        readWriteLock.readLock().lock(10, TimeUnit.SECONDS);
        String num = stringRedisTemplate.opsForValue().get("num");
        return num;
    }

    @Override
    public void testWriteLock() {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("anyRWLock");
        readWriteLock.writeLock().lock(10, TimeUnit.SECONDS);
        stringRedisTemplate.opsForValue().set("num",UUID.randomUUID().toString());
    }

    @Override
    public void freeMarkTest() {
        try {
            //创建了一个Configuration对象，里面是freeMark的版本号
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
            //获取文件路径
            ClassLoader classLoader = getClass().getClassLoader();
            URL template1 = classLoader.getResource("template");
            //设置模板路径
            configuration.setDirectoryForTemplateLoading( new File(template1.getFile()));
            //设置字符集
            configuration.setDefaultEncoding("utf-8");
            //加载模板创建模板对象

            Template template = configuration.getTemplate("template/hello.ftl");
            //创建模板使用的数据集
            FreeMarkVO freeMarkVO=new FreeMarkVO();
            freeMarkVO.setName("段子阳");
            //创建Writer，输出对象
            StringWriter stringWriter = new StringWriter();
            BufferedWriter writer = new BufferedWriter(stringWriter);
            template.process(freeMarkVO, writer);
            String s = stringWriter.toString();
            System.out.println(s+"***************************");
            StringReader reader = new StringReader(s);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }

    }


//redis 实现锁
//    @Override
//    public void testLock() {
//        String uuid = UUID.randomUUID().toString();
//        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 3L, TimeUnit.SECONDS);
//        if (flag) {
//            String num = stringRedisTemplate.opsForValue().get("num");
//            if (StringUtils.isEmpty(num)) {
//                return;
//            }
//            int numValue = Integer.parseInt(num);
//            stringRedisTemplate.opsForValue().set("num", String.valueOf(++numValue));
////            if(stringRedisTemplate.opsForValue().get("lock").equals(uuid)){
////                stringRedisTemplate.delete("lock");
////            }
//            //使用LUA脚本使lock更加健壮
//            String scrip = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
//
//            DefaultRedisScript redisScript = new DefaultRedisScript(scrip);
//            stringRedisTemplate.execute(redisScript, Arrays.asList("lock"), uuid);
//        } else {
//            try {
//                Thread.sleep(500);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            testLock();
//        }
//    }
}